from google.cloud import storage
import datetime
from django.conf import settings
from storages.backends.gcloud import GoogleCloudStorage


storage_client = storage.Client(credentials=settings.GS_CREDENTIALS)


def generate_assigned_url(filename: str, expiration_hours: int = 168) -> str:
    try:
        bucket = storage_client.get_bucket(settings.GS_BUCKET_NAME)
        blob = bucket.blob(filename)

        url_expiry = datetime.datetime.utcnow() + datetime.timedelta(hours=expiration_hours)  # URL expiration time
        url = blob.generate_signed_url(
            version="v4",
            # This URL is valid for 1 hour
            expiration=url_expiry,
            # Allow GET requests using this URL.
            method="GET",
        )
        return url
    except:
        return False


storage = GoogleCloudStorage()


def delete_file(file_path: str) -> bool:
    try:
        storage.delete(file_path)
        return True, 'success'
    except Exception as e:
        return False, str(e)


def upload_file(file: object, target_path: str) -> str:
    path = storage.save(target_path, file)
    return storage.url(path)